<?php
/**
 * Created by PhpStorm.
 * User: Rei
 * Date: 16/5/12
 * Time: 19:36
 * Mail: rei@king.moe
 */

namespace Home\Model;

use Think\Model;

class NewsModel extends Model
{


    public function getNews($id)
    {
        if (session('?uid')) {
            $uid = session('uid');
            $data = $this->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')->field("nid, title, relink, content, publisher, pubtime, topic, name, likes, (select count(*) from pin_like where uid=$uid and nid=$id) AS islike, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments")->find($id);
            if (!empty($data)) {
                $data['pubtime'] = date('n/j/Y', $data['pubtime']);
            }
        }else{
            $data = $this->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')->field('nid, title, relink, content, publisher, pubtime, topic, name, likes, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments')->find($id);
            if (!empty($data)) {
                $data['pubtime'] = date('n/j/Y', $data['pubtime']);
            }
        }
        $data["relink"] = json_decode($data["relink"], true);

        return $data;
    }

    public function getWaterfallData($page, $size, $type, $keyword="")
    {
        $page = ($page - 1) * $size;
        $db_prefix = C('DB_PREFIX'); // 表前缀

        if (session('?uid')) {
            $uid = session('uid');
            switch($type){
                case "find" :
                    $cookie = cookie('track');
                    if($cookie){
                        $track = json_decode($cookie, true);
                        arsort($track, SORT_NUMERIC);
                        $topics = implode(",",array_keys($track));
                        $data = $this->where("topic in ($topics) AND (name like '%$keyword%' or title like '%$keyword%' or publisher like '%$keyword%')")
                            ->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')
                            ->field("nid as id,title,left(content,200) as content,publisher,pubtime,topic,name,likes,(select count(*) from pin_like where uid=$uid and nid=pin_news.nid) AS islike, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments")
                            ->order("FIELD(`topic`, $topics)")
                            ->limit($page, $size)
                            ->select();
                    }else{
                        $data = $this->where("name like '%$keyword%' or title like '%$keyword%' or publisher like '%$keyword%'")
                            ->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')
                            ->field("nid as id,title,left(content,200) as content,publisher,pubtime,topic,name,likes,(select count(*) from pin_like where uid=$uid and nid=pin_news.nid) AS islike, (select count(*) from pin_like where uid=$uid and nid=pin_news.nid) AS islike, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments")
//                     ->order("$order_key " . $sort_type)
                            ->limit($page, $size)
                            ->select();
                    }
                    break;
                case "subscribe" :
                    $data = $this->where($db_prefix . "news.topic IN (SELECT tid FROM " . $db_prefix . "subscribe WHERE uid=$uid) AND (name like '%$keyword%' or title like '%$keyword%' or publisher like '%$keyword%')")
                        ->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')
                        ->field("nid as id,title,left(content,200) as content,publisher,pubtime, topic,name,likes, (select count(*) from pin_like where uid=$uid and nid=pin_news.nid) AS islike, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments")
//                     ->order("$order_key " . $sort_type)
                        ->limit($page, $size)
                        ->select();
                    break;
                case "like" :
                    $data = $this->where($db_prefix . "news.nid IN (SELECT nid FROM " . $db_prefix . "like WHERE uid=$uid)")
                        ->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')
                        ->field("nid as id,title,left(content,200) as content,publisher,pubtime, topic,name,likes, (select count(*) from pin_like where uid=$uid and nid=pin_news.nid) AS islike, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments")
//                     ->order("$order_key " . $sort_type)
                        ->limit($page, $size)
                        ->select();
                    break;
                default :
                    $data = $this->where("name like '%$keyword%' or title like '%$keyword%' or publisher like '%$keyword%'")
                        ->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')
                        ->field("nid as id,title,left(content,200) as content,publisher,pubtime,topic,name,likes, (select count(*) from pin_like where uid=$uid and nid=pin_news.nid) AS islike, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments")
//                     ->order("$order_key " . $sort_type)
                        ->limit($page, $size)
                        ->select();
                    break;
            }
        } else {
            $data = $this->where("")
                ->join('__TOPIC__ ON __TOPIC__.tid = __NEWS__.topic', 'LEFT')
                ->field('nid as id,title,left(content,200) as content,publisher,pubtime,topic,name,likes, (select count(*) from pin_comment where thread_key=pin_news.nid) AS comments')
//                     ->order("$order_key " . $sort_type)
                ->limit($page, $size)
                ->select();
        }

        return $data;
    }

    public function getMaxPage($size)
    {

        $count = $this->where('')->count();
        $max_page = intval(ceil($count / $size));

        return $max_page;
    }


    //添加评论
    public function addComments($meta)
    {
        if ($meta) {
            $data = array(
                'post_id' => $meta['post_id'],
                'parent_id' => $meta['parent_id'] == '' ? 0 : $meta['parent_id'],
                'thread_key' => $meta['thread_key'],
                'message' => $meta['message'],
                'created_at' => strtotime($meta['created_at'])
            );
            return D('Comment')->data($data)->add();
        }
        return '没有文章记录';
    }


    //删除评论
    public function deleteComments($meta)
    {
        if ($meta) {
            $post_id = implode(',', $meta);
            return D('Comment')->delete($post_id);
        }
        return '没有文章记录';
    }


    //喜欢&不喜欢
    public function like($nid, $action)
    {
        $uid = session('uid');
        switch($action){
            case 'like':
                $this->execute("update __NEWS__ set `likes` = `likes`+1 WHERE `nid` = $nid");
                return D('Like')->data(array('uid'=>$uid, 'nid'=>$nid))->add();
                break;
            case 'unlike':
                $this->execute("update __NEWS__ set `likes` = IF(`likes`<1, 0, `likes`-1) WHERE `nid` = $nid");
                return D('Like')->where(array('uid'=>$uid, 'nid'=>$nid))->delete();
                break;
            default :
                break;
        }
        return false;
    }

    //查询最新更新的文章
    public function getLatestNews($time){
        $data = array();
        if(session('?uid')){
            $uid = session('uid');
            if(!$time){
                $time = time();
            }
            $time = $time - 30;
            $data = $this->query("SELECT nid, title, pubtime, (SELECT name FROM __TOPIC__ WHERE __TOPIC__.tid = topic) AS name FROM __NEWS__ LEFT JOIN __SUBSCRIBE__ ON __SUBSCRIBE__.tid = topic WHERE pubtime>$time AND __SUBSCRIBE__.uid=$uid");
        }
        return $data;
    }

}